//
//  LPTDiagnosisDetailViewController.m
//  LPTClient
//
//  Created by mac on 2018/12/8.
//  Copyright © 2018年 zhaodd. All rights reserved.
//

#import "LPTDiagnosisDetailViewController.h"
#import "LPTDiagnosisTableFooterView.h"
#import "LPTDiagnosisTableViewCell.h"
#import "LPTVisitTimeTableViewCell.h"
#import "LPTMedicineCountTableViewCell.h"
#import "LPTAddMedicineTableViewCell.h"
#import "LPTMedicineConfirmTableViewCell.h"
#import "LPTpreamountTableViewCell.h"
#import "LPTPreUseTableViewCell.h"
#import "LPTPreManageViewController.h"
#import "LPTMediModel.h"
#import "LPTCategoryModel.h"

@interface LPTDiagnosisDetailViewController ()<UITableViewDelegate,UITableViewDataSource,LPTDiagnosisTableFooterViewDelegate,LPTPreManageViewControllerDelegate,LPTMedicineConfirmTableViewCellDelegate,LPTMedicineCountTableViewCellDelegate,UIPickerViewDelegate,UIPickerViewDataSource>

@property (nonatomic,strong)NSDictionary *chufangDic;
@property (nonatomic,weak)UIDatePicker *picker;
@property (nonatomic,weak)UIPickerView *medicinePicker;
@property (nonatomic,weak)UIView *pickBackView;
@property (nonatomic,strong)NSMutableArray *chufangIdentifyArray;
@property (nonatomic,strong)NSMutableArray <LPTMediModel *> *selectMedicineArray;
@property (nonatomic,copy)NSArray *categorysArray;//药品列表
@property (nonatomic,assign)NSInteger selectCatIndex;//当前选择的药品分类
@property (nonatomic,strong)LPTMedicineModel *selectMediModel;//当前选择的药品模型
@property (nonatomic,assign)LPTConfirmType confrimType;
@property (nonatomic,weak)UIToolbar *toolBar;

@end

@implementation LPTDiagnosisDetailViewController

-(UIView *)pickBackView
{
    if (!_pickBackView) {
        
        UIView *backView = [[UIView alloc] initWithFrame:self.view.bounds];
        [self.view addSubview:backView];
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
            
            [self showPickView:NO];
        }];
        [backView addGestureRecognizer:tapGesture];
        backView.backgroundColor = [UIColor colorWithWhite:.6 alpha:.3];
        _pickBackView = backView;
    }
    
    return _pickBackView;
}

-(UIToolbar *)toolBar
{
    if (!_toolBar) {
        
        UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 80, kScreenWidth, 44)];
        toolbar.barStyle = UIBarStyleDefault;
        toolbar.backgroundColor = [UIColor whiteColor];
        UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelAction)];
         UIBarButtonItem *space = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:NULL];
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(sureAction)];
        toolbar.items = @[leftItem,space,rightItem];
        [self.pickBackView addSubview:toolbar];
        _toolBar = toolbar;
    }
    
    return _toolBar;
}

-(UIDatePicker *)picker
{
    if (!_picker) {
        UIDatePicker *picker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, self.view.height - 300, kScreenWidth, 300)];
        picker.backgroundColor = [UIColor whiteColor];
        [picker setCalendar:[NSCalendar currentCalendar]];
        [picker setDate:[NSDate date]];
        [picker setDatePickerMode:UIDatePickerModeDate];
        [picker addTarget:self action:@selector(dateChange:)forControlEvents:UIControlEventValueChanged];
        [self.pickBackView addSubview:picker];
        _picker = picker;
    }
    
    return _picker;
}

-(UIPickerView *)medicinePicker
{
    if (!_medicinePicker) {
        UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, self.view.height - 300, kScreenWidth, 300)];
        pickerView.backgroundColor = [UIColor whiteColor];
        pickerView.dataSource = self;
        pickerView.delegate = self;
        [self.pickBackView addSubview:pickerView];
        _medicinePicker = pickerView;
    }
    
    return _medicinePicker;
}

-(void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initSubViews];
    
    self.selectCatIndex = 0;
    self.confrimType = kConfirmType;
    self.selectMedicineArray = [NSMutableArray new];
    self.chufangIdentifyArray = [[NSMutableArray alloc] init];
    
    [self.chufangIdentifyArray addObject:@"LPTVisitTimeTableViewCell"];
    
    [self requestprescriptionList];
}

-(BOOL)navigationShouldPopOnBackButton
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您正在编辑诊断信息，确定要返回吗？" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self.navigationController popViewControllerAnimated:YES];
        
    }]];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
    
    return NO;
}

-(void)initSubViews
{
    LPTDiagnosisTableFooterView *footerView = [[LPTDiagnosisTableFooterView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 80)];
    footerView.delegate = self;
    self.tableView.tableFooterView = footerView;
    
    [self.dataSource addObjectsFromArray:@[@"诊断",@"",@"",@"医嘱"]];
    [self.tableView reloadData];
}

//获取中药列表
-(void)requestprescriptionList
{
    LPTBaseRequest *request = [[LPTBaseRequest alloc] initWithApi:@"/api/chinese_medicine_categories" withBody:@{}];
    [request startRequestCompleteSuccess:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        
        self.categorysArray = [NSArray modelArrayWithClass:[LPTCategoryModel class] json:data[@"chinese_medicine_categories"]];
        
    } completeFailed:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        
    }];
}

#pragma mark - UIToolBarAction
//取消
-(void)cancelAction
{
    [self showMedicineList:NO];
}

//确定
-(void)sureAction
{
    [self showMedicineList:NO];
    
    if (self.selectMediModel) {
        [self.selectMedicineArray addObject:[LPTMediModel modelWithMedicineModel:self.selectMediModel]];
        [self.chufangIdentifyArray insertObject:@"LPTMedicineCountTableViewCell" atIndex:self.selectMedicineArray.count];
        [self.tableView insertRowAtIndexPath:[NSIndexPath indexPathForRow:self.selectMedicineArray.count inSection:2] withRowAnimation:UITableViewRowAnimationNone];
//        [self.tableView reloadSection:2 withRowAnimation:UITableViewRowAnimationNone];
    }
}

//提交结果
-(void)takeResult
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    //药方id
    if (self.visit_id) {
        [params setValue:self.visit_id forKey:@"visit_id"];
    }
    
    //诊断结果
    LPTDiagnosisTableViewCell *cell1 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    NSString *zhenduanStr = cell1.textView.text;
    if (!zhenduanStr.length) {
        [MMProgressHUD show];
        [MMProgressHUD dismissWithError:@"请先输入诊断结果"];
        return;
    }
    [params setValue:zhenduanStr forKey:@"diagnosis"];
    
    //医嘱
    LPTDiagnosisTableViewCell *cell4 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:3]];
    NSString *yizhu = cell4.textView.text;
    if (!yizhu.length) {
        [MMProgressHUD show];
        [MMProgressHUD dismissWithError:@"请先输入医嘱"];
        return;
    }
    [params setValue:yizhu forKey:@"advice"];
    
    //复诊日期
    LPTVisitTimeTableViewCell *dateCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
    if ([dateCell.detailLabel.text isEqualToString:@"请选择时间"]) {
        [MMProgressHUD show];
        [MMProgressHUD dismissWithError:@"请先选择复诊日期"];
        return;
    }
    [params setValue:dateCell.detailLabel.text forKey:@"revisit_date"];
    
    if (self.selectMedicineArray.count && self.chufangDic) {
        
        //是否选择药方
        [params setValue:@(1) forKey:@"prescriptionable"];
        
        //成分
        [params setValue:[self getRecipeItemArray] forKey:@"recipe_items"];
        
        //处方id
//        NSString *chufangid = self.chufangDic[@"id"];
        
        //剂量
        LPTpreamountTableViewCell *amountCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.chufangIdentifyArray.count - 2 inSection:2]];
        [params setValue:@(amountCell.count) forKey:@"quantity"];
        
        //用法
        LPTPreUseTableViewCell *useCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.chufangIdentifyArray.count - 1 inSection:2]];
        if (!useCell.textField.text.length) {
            [MMProgressHUD show];
            [MMProgressHUD dismissWithError:@"请先填写用法"];
            return;
        }
        
        [params setValue:useCell.textField.text forKey:@"usage"];
        
    }else{
        
        [params setValue:@(0) forKey:@"prescriptionable"];
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    LPTBaseRequest *request = [[LPTBaseRequest alloc] initWithApi:@"/api/diagnosis" withBody:params withMethod:YTKRequestMethodPOST];
    [request startRequestCompleteSuccess:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MMProgressHUD show];
        [MMProgressHUD dismissWithSuccess:@"提交成功"];
        [self.navigationController popViewControllerAnimated:YES];
        
    } completeFailed:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MMProgressHUD show];
        [MMProgressHUD dismissWithError:data];
    }];
}

//获取成分列表
-(NSArray *)getRecipeItemArray
{
    NSMutableArray *array = [NSMutableArray new];
    for (LPTMediModel *model in self.selectMedicineArray) {
        NSDictionary *dic = @{[NSString stringWithFormat:@"%@",model.chinese_medicine.mediId]:@(model.weight)};
        [array addObject:dic];
    }
    
    return [array copy];
}

//是否展示picker
-(void)showPickView:(BOOL)show
{
    if (show) {
        
        [self dateChange:self.picker];
        
    }else{
        
        [self.picker removeFromSuperview];
        [self.pickBackView removeFromSuperview];
    }
}

//是否展示药方列表
-(void)showMedicineList:(BOOL)show
{
    if (show) {
        
        LPTCategoryModel *catModel = self.categorysArray[self.selectCatIndex];
        self.selectMediModel = (LPTMedicineModel *)[catModel.chinese_medicines firstObject];
        self.toolBar.bottom = self.medicinePicker.top;
        self.medicinePicker.hidden = NO;
        
    }else{
        
        [self.medicinePicker removeFromSuperview];
        [self.pickBackView removeFromSuperview];
    }
}

-(void)dateChange:(UIDatePicker *)picker
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];//创建一个日期格式化器
    
    dateFormatter.dateFormat=@"yyyy-MM-dd";
    
    LPTVisitTimeTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
    
    cell.detailLabel.text = [dateFormatter stringFromDate:picker.date];
}

#pragma mark - UIPickerViewDataSource & Delegate
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        return self.categorysArray.count;
    }else{
        
        LPTCategoryModel *model = self.categorysArray[self.selectCatIndex];
        return model.chinese_medicines.count;
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    return kScreenWidth/2;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 44.0f;
}

- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    LPTCategoryModel *model = self.categorysArray[row];
    
    if (component == 0) {
        
        return model.name;
    }else{
        
        if (row < model.chinese_medicines.count) {
            
            LPTMedicineModel *medicine = model.chinese_medicines[row];
            return medicine.name;
        }
        
        return @"";
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {
        self.selectCatIndex = row;
        [pickerView reloadComponent:1];
    }else{
        
        LPTCategoryModel *model = self.categorysArray[self.selectCatIndex];
        LPTMedicineModel *mediModel = model.chinese_medicines[row];
        self.selectMediModel = mediModel;
    }
}

#pragma mark - UITableViewDataSource & Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSource.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (section == 2) {
        return self.chufangIdentifyArray.count;
    }
    
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 || indexPath.section == 3) {
        
        LPTDiagnosisTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LPTDiagnosisTableViewCell" forIndexPath:indexPath];
        
        if (indexPath.section == 0) {
            cell.placeHolder.text = @"请输入对患者的诊断信息";
            
        }else{
            cell.placeHolder.text = @"请输入对患者的嘱咐信息";
            
        }
        return cell;
        
    }else if (indexPath.section == 2){
        
        NSString *identify = self.chufangIdentifyArray[indexPath.row];
        if ([identify isEqualToString:@"LPTVisitTimeTableViewCell"]) {
            
            LPTVisitTimeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LPTVisitTimeTableViewCell" forIndexPath:indexPath];
            
            cell.titleLab.text = @"处方";
            
            if (self.chufangDic) {
                
                cell.detailLabel.text = self.chufangDic[@"name"];
                
            }else{
                
                cell.detailLabel.text = @"请选择处方";
            }
            
            return cell;
            
        }else if([identify isEqualToString:@"LPTMedicineCountTableViewCell"]){
            
            LPTMedicineCountTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LPTMedicineCountTableViewCell" forIndexPath:indexPath];
            cell.delegate = self;
            cell.edit = (self.confrimType == kEditType);
            [cell refreshWithEntity:self.selectMedicineArray[indexPath.row - 1]];
            return cell;
            
        }else if ([identify isEqualToString:@"LPTAddMedicineTableViewCell"]){
            
            LPTAddMedicineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LPTAddMedicineTableViewCell" forIndexPath:indexPath];
            
            return cell;
        }else if ([identify isEqualToString:@"LPTMedicineConfirmTableViewCell"]){
            
            LPTMedicineConfirmTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LPTMedicineConfirmTableViewCell" forIndexPath:indexPath];
            cell.type = self.confrimType;
            cell.delegate = self;
            return cell;
            
        }else if ([identify isEqualToString:@"LPTpreamountTableViewCell"]){
            
            LPTpreamountTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LPTpreamountTableViewCell" forIndexPath:indexPath];
            return cell;
        }else{
            
            LPTPreUseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LPTPreUseTableViewCell" forIndexPath:indexPath];
            return cell;
        }
        
    }else{
        
        LPTVisitTimeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LPTVisitTimeTableViewCell" forIndexPath:indexPath];
            
            cell.titleLab.text = @"复诊时间";
            cell.detailLabel.text = @"请选择时间";
        
        return cell;
    }
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @"诊断";
    }else if (section == 3){
        return @"医嘱";
    }
    
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0 || section == 3) {
        return 40;
    }else{
        return 8;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 || indexPath.section == 3) {
        return 115;
    }else{
        return 44;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 1) {
        
        [self showPickView:YES];
        
    }else if(indexPath.section == 2){
        
        NSString *identify = [self.chufangIdentifyArray objectAtIndex:indexPath.row];
        
        if ([identify isEqualToString:@"LPTVisitTimeTableViewCell"]) {
            
            //跳转到处方管理
            LPTPreManageViewController *managerVC = [LPTPreManageViewController instantiate];
            managerVC.type = kSelectType;
            managerVC.delegate = self;
            [self.navigationController pushViewController:managerVC animated:YES];
            
        }else if ([identify isEqualToString:@"LPTAddMedicineTableViewCell"]){
            
            [self showMedicineList:YES];
        }
    }
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self.view endEditing:YES];
}

#pragma mark - LPTDiagnosisTableFooterDelegate
-(void)diagnosisTableFooterViewDidClickTakeBtn
{
    
    [self takeResult];
    
}

#pragma mark - LPTmedicineCountTableViewCell
-(void)medicineCountTableViewCell:(LPTMedicineCountTableViewCell *)cell didDeleteModel:(LPTMediModel *)model
{
    if ([self.selectMedicineArray containsObject:model]) {
        
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        [self.selectMedicineArray removeObject:model];
        [self.chufangIdentifyArray removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationNone];
    }
}

#pragma mark - PreManageViewControllerDelegate
-(void)preManageViewControllerDidSelectItem:(NSDictionary *)entity
{
    self.chufangDic = entity;
    
    [self.chufangIdentifyArray removeAllObjects];
    [self.chufangIdentifyArray addObject:@"LPTVisitTimeTableViewCell"];
    
    NSArray *mediArray = [NSArray modelArrayWithClass:LPTMediModel.class json:entity[@"recipe_items"]];
    [self.selectMedicineArray addObjectsFromArray:mediArray];
    
    for (NSDictionary *dic in entity[@"recipe_items"]) {
        NSLog(@"-----%@",dic);
        [self.chufangIdentifyArray addObject:@"LPTMedicineCountTableViewCell"];
    }
    
    [self.chufangIdentifyArray addObject:@"LPTMedicineConfirmTableViewCell"];
    
    [self.chufangIdentifyArray addObject:@"LPTpreamountTableViewCell"];
    
    [self.chufangIdentifyArray addObject:@"LPTPreUseTableViewCell"];
    
    [self.tableView reloadSection:2 withRowAnimation:UITableViewRowAnimationNone];
}

-(void)medicineConfirmTableViewCell:(LPTMedicineConfirmTableViewCell *)cell didclickAtIndex:(NSInteger)index
{
    if (index == 0) {
        
        //删除
        self.chufangDic = nil;
        self.selectCatIndex = 0;
        self.selectMediModel = nil;
        [self.selectMedicineArray removeAllObjects];
        [self.chufangIdentifyArray removeAllObjects];
        [self.chufangIdentifyArray addObject:@"LPTVisitTimeTableViewCell"];
        [self.tableView reloadSection:2 withRowAnimation:UITableViewRowAnimationNone];
        
    }else{
        
        //确定
        if (cell.type == kEditType) {
            self.confrimType = kConfirmType;
            
            if ([self.chufangIdentifyArray containsObject:@"LPTAddMedicineTableViewCell"]) {
                
                NSInteger index = [self.chufangIdentifyArray indexOfObject:@"LPTAddMedicineTableViewCell"];
                [self.chufangIdentifyArray removeObject:@"LPTAddMedicineTableViewCell"];
                [self.tableView deleteRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:2] withRowAnimation:UITableViewRowAnimationNone];
                [self.tableView reloadSection:2 withRowAnimation:UITableViewRowAnimationNone];
            }
            
        }else{
            
            self.confrimType = kEditType;
            
            [self.chufangIdentifyArray insertObject:@"LPTAddMedicineTableViewCell" atIndex:self.selectMedicineArray.count + 1];
            [self.tableView insertRowAtIndexPath:[NSIndexPath indexPathForRow:self.selectMedicineArray.count + 1 inSection:2] withRowAnimation:UITableViewRowAnimationNone];
            [self.tableView reloadSection:2 withRowAnimation:UITableViewRowAnimationNone];
        }
        
    }
}

@end
